import React from "react"
import { Pie, Gauge } from "@ant-design/charts"
import { PieConfig } from "@ant-design/charts/es/pie"
import { AuditRefs, Categories } from "@/models/detail-result"
import styled from "styled-components"
import { GaugeConfig } from "@ant-design/charts/es/gauge"

const StyledChartContainer = styled.div`
  display: flex;
`

function filterAuditData(auditRefs: AuditRefs[], audits: any) {
  return auditRefs
    ?.filter((it) => it.weight !== 0)
    .map((it) => {
      // @ts-ignore
      it.score = Math.round(audits[it.id].score * 100)
      return it
    })
}

export const ScoreBoard: React.FC<{ info?: Categories; audits: any }> = ({
  info,
  audits,
}) => {
  const pieConfig: PieConfig = {
    angleField: "weight",
    colorField: "id",
    radius: 1,
    innerRadius: 0.64,
    data: filterAuditData(info?.performance.auditRefs || [], audits) || [],
    statistic: {
      title: false,
      content: {
        style: {
          whiteSpace: "pre-wrap",
          overflow: "hidden",
          textOverflow: "ellipsis",
        },
        formatter: () => `性能打分\n${Number(info?.performance.score) * 100}`,
      },
    },
    label: {
      type: "inner",
      offset: "-50%",
      formatter: (item) => {
        return `${item.score}分`
      },
      style: {
        textAlign: "center",
        fontSize: 14,
      },
    },
    interactions: [{ type: "element-selected" }, { type: "element-active" }],
    legend: {
      layout: "vertical",
      position: "right",
    },
    // padding: [0, 150, 0, 0],
    // appendPadding: 10,
    style: {
      height: 350,
    },
  }

  const percent = info?.performance.score || 0
  const ticks = [0, 1 / 4, 5 / 6, 1]
  const color = ["#F4664A", "#FAAD14", "#30BF78"]

  const scoreConfig: GaugeConfig = {
    percent: percent,
    range: {
      ticks: ticks,
      color: color,
    },
    statistic: {
      title: {
        formatter: () => {
          if (percent < ticks[1]) {
            return "差"
          }
          if (percent < ticks[2]) {
            return "良好"
          }
          return "优秀"
        },
        style: () => {
          return {
            fontSize: "36px",
            lineHeight: 1,
            color:
              percent < ticks[1]
                ? color[0]
                : percent < ticks[2]
                ? color[1]
                : color[2],
          }
        },
      },
      content: {
        offsetY: 36,
        style: {
          fontSize: "24px",
          color: "#4B535E",
        },
        formatter: () => "系统表现",
      },
    },
    style: {
      height: 300,
      paddingTop: "50px",
    },
  }

  return (
    <StyledChartContainer className="mb-10">
      <div style={{ width: "50%" }}>{info && <Pie {...pieConfig} />}</div>
      <div style={{ width: "50%" }}>{info && <Gauge {...scoreConfig} />}</div>
    </StyledChartContainer>
  )
}
